package repository

import (
	"context"
	"jk-time/webook/account/cache"
	"jk-time/webook/account/dao"
	"jk-time/webook/account/domain"
	"time"
)

type AccountRepository interface {
	AddCredit(ctx context.Context, creadit domain.Creadit) error
	SetCacheAccount(ctx context.Context, biz string, id int64) error
	Verify(ctx context.Context, biz string, id int64) bool
}
type accountRepository struct {
	dao   dao.AccountDao
	cache cache.AccountCache
}

func NewAccountRepository(dao dao.AccountDao, cache cache.AccountCache) AccountRepository {
	return &accountRepository{dao: dao, cache: cache}
}

func (a *accountRepository) AddCredit(ctx context.Context, creadit domain.Creadit) error {
	acts := make([]dao.AccountActivity, 0, len(creadit.Items))
	now := time.Now().UnixMilli()
	for _, itm := range creadit.Items {
		acts = append(acts, dao.AccountActivity{
			Uid:         itm.Uid,
			Biz:         creadit.Biz,
			BizId:       creadit.BizId,
			Account:     itm.Account,
			AccountType: itm.AccountType.AsUint8(),
			Amount:      itm.Amt,
			Currency:    itm.Currency,
			Ctime:       now,
			Utime:       now,
		})
	}
	return a.dao.AddActivities(ctx, acts...)
}
func (a *accountRepository) SetCacheAccount(ctx context.Context, biz string, id int64) error {
	return a.cache.SetCacheAccount(ctx, biz, id)
}
func (a *accountRepository) Verify(ctx context.Context, biz string, id int64) bool {
	ok := a.cache.HasCacheAccount(ctx, biz, id)
	if ok {
		return true
	}
	err := a.dao.GetFirstAccount(ctx, biz, id)
	if err == nil {
		go func() {
			_ = a.cache.SetCacheAccount(ctx, biz, id)
		}()
		return true
	}
	return false
}
